package com.testing.myview_demo;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

/**
 * Created by Administrator on 2017/3/5.
 */

public class MyView extends View {

    private float inR;
    private float outR;
    private String textContent;
    private int textSize;
    private int outColor;
    Context context;

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.myView);

        inR = typedArray.getDimension(R.styleable.myView_inR, 50);
        outR = typedArray.getDimension(R.styleable.myView_outR, 100);
        textContent = typedArray.getString(R.styleable.myView_textContent);
        textSize = typedArray.getDimensionPixelSize(R.styleable.myView_textSize, 30);
        outColor = typedArray.getColor(R.styleable.myView_outColor, Color.YELLOW);

        typedArray.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint p = new Paint();
        p.setColor(outColor);

        canvas.drawCircle(getWidth() / 2, getHeight() / 2, outR, p);

        p.setColor(Color.WHITE);

        canvas.drawCircle(getWidth() / 2, getHeight() / 2, inR, p);

        p.setColor(Color.BLACK);

        Rect rect = new Rect();
        p.getTextBounds(textContent, 0, textContent.length(), rect);
        canvas.drawText(textContent, getWidth() / 2 - rect.width() / 2, getHeight() / 2 + rect.height() / 2, p);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                float x = event.getX();
                float y = event.getY();

                float x2 = getWidth() / 2 - x;
                float y2 = getHeight() / 2 - y;

                float v = x2 * x2 + y2 * y2;
                double sqrt = Math.sqrt(v);

                if (sqrt <= inR) {
                    Toast.makeText(context, "在小圆内", Toast.LENGTH_SHORT).show();
                } else if (sqrt > inR && sqrt <= outR) {
                    Toast.makeText(context, "在圆环内", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "在圆环外", Toast.LENGTH_SHORT).show();
                }

                break;
        }


        return true;
    }
}
